from sqlalchemy.orm import Session
from app.backend.db_depends import get_db
from app.backend.db import SessionLocal
from typing import Annotated
import redis
from app.models import *
from sqlalchemy import insert, select, delete

from fastapi import APIRouter, Depends, status, HTTPException
from celery import Celery
from pytesseract import pytesseract
from PIL import Image
from app.config import REDIS_HOST, REDIS_PORT

router = APIRouter(prefix='/documents_text', tags=['documents_text'])

celery = Celery('doc_analise', broker=f'redis://{REDIS_HOST}:{REDIS_PORT}')


@celery.task
def create_text(path: str, doc_id: int):
    pytesseract.tesseract_cmd = "/usr/bin/tesseract"
    with Image.open(path) as img:
        res = pytesseract.image_to_string(img, lang="eng+rus")
        with SessionLocal() as session:
            session.execute(insert(Documents_text).values(id_doc=doc_id, text=res))
            session.commit()


@router.post('/doc_analyse',
             description='Recognizing text from an image and saving it to the database',
             summary='Text recognition')
def create_text_doc(doc_id: int, db: Annotated[Session, Depends(get_db)]) -> dict:
    path = db.scalar(select(Documents.path).where(Documents.id == doc_id))
    if not path:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail='There is no such document'
        )
    create_text.delay(path, doc_id)

    return {
        'status_code': status.HTTP_200_OK,
        'transaction': 'The text has been added to the Documents_text table'
    }

@router.get('/get_text',
            description='Getting text from an image by id',
            summary='Getting recognized text')
def get_text_doc(doc_id: int, db: Annotated[Session, Depends(get_db)]) -> dict:
    doc = db.scalar(select(Documents_text.text).where(Documents_text.id_doc == doc_id))
    if not doc:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail='There is no text for such a document yet'
        )
    return {f'The text of the document with id {doc_id}': doc}